package com.tq.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.tq.application.TAppConstant;

public class ImgUtil 
{

	private Context context;
	
	public ImgUtil() {
		super();
	}


	public ImgUtil(Context context) {
		super();
		this.context = context;
	}


	public File creFile(String filename )throws IOException 
	{
		
		File dir = new File(TAppConstant.PATH);
		if(!dir.exists())
		{
			dir.mkdir();
		}
		File file = new File(TAppConstant.PATH+filename);
		file.createNewFile();
		return file;
	}
	

	public boolean isFileExist(String filename) 
	{
		File file = new File(TAppConstant.PATH+filename);
		return file.exists();
	}
	
	public Bitmap getBitmapFromSd(String url)
	{
		Bitmap bit = null;
		String filename=MD5Util.getMD5Str(getImgName(url));
		if(!isFileExist(filename))
		{
			return null;
		}
		else {
			
			String imgPath = TAppConstant.PATH+filename;
			try {
				FileInputStream fis = new FileInputStream(imgPath);
				
				bit = BitmapFactory.decodeStream(fis);
				
				fis.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return bit;
		}
	}
	
	public void writeBitmap2Sd(String url,Bitmap bitmap)
	{
		
		
		
		String filename=MD5Util.getMD5Str(getImgName(url));
		
		File file;
		
		FileOutputStream output = null;
		ByteArrayOutputStream baos =null;
		try 
		{	
			file=creFile(filename);
			
			baos= new ByteArrayOutputStream();
			
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			output = new FileOutputStream(file);
			output.write(baos.toByteArray());
			
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public String getImgName(String url)
	{
		int start=url.lastIndexOf("/");
		
		String str=url.substring(start);
		return str;
	}
	
	
	
	
	
}
